package edu.gatech.cs2340.aperturescience;

import edu.gatech.cs2340.aperturescience.backend.login.SQLUsersDataSource;
import edu.gatech.cs2340.aperturescience.backend.login.User;
import edu.gatech.cs2340.aperturescience.backend.login.UsersDataSource;
import edu.gatech.cs2340.aperturescience.map.MyGoogleMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

/**
 * Main class for Login screen.
 * 
 * @author Kefu Zhou, Kevin Lacey, Jacob Morgan, Kelly Evanish
 * 
 */

public class TaskManager extends Activity {

	// Declare our Views, so we can access them later
	private EditText etUsername;
	private EditText etPassword;
	private Button btnLogin;
	private Button btnRegister;
	private TextView lblResult;
	private PopupWindow popup;
	private View popupView;

	private UsersDataSource userList;

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (userList != null) {
			userList.close();
		}
	}
	
	//for JUnit tests
	public View getLoginPopup()
	{
		return popupView;
	}

	/**
	 * Called when the activity is first created.
	 * 
	 * */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		userList = new SQLUsersDataSource(this);
		userList.open();

		// Get the EditText and Button References
		etUsername = (EditText) findViewById(R.id.username);
		etPassword = (EditText) findViewById(R.id.password);
		btnLogin = (Button) findViewById(R.id.login_button);
		btnRegister = (Button) findViewById(R.id.register_button);
		lblResult = (TextView) findViewById(R.id.result);

		// test

		Button testButton = (Button) findViewById(R.id.test_button);

		testButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(TaskManager.this, MyGoogleMap.class);
				startActivity(i);
			}
		});

		/**
		 * Set Click Listener
		 */
		btnRegister.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showPopup();
			}
		});

		/**
		 * Set Click Listener
		 */
		btnLogin.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// Check Login
				String username = etUsername.getText().toString();
				String password = etPassword.getText().toString();

				User user = userList.getUser(username, password);
				etUsername.getText().clear();
				etPassword.getText().clear();
				if (user != null) {
					lblResult.setText("Login successful.");
					Intent i = new Intent(TaskManager.this,
							CategoryViewActivity.class);
					i.putExtra("edu.gatech.cs2340.aperturescience.uid",
							user.getID());
					startActivity(i);

				} else {
					lblResult.setText("Login failed. "
							+ "Username and/or password doesn't match.");
				}
			}
		});
	}

	/**
	 * Shows message for validating user account.
	 * 
	 * @param user
	 *            user's username
	 * @param password
	 *            user's password
	 * @param email
	 *            user's email
	 * @param name
	 *            user's name
	 * @return the messages
	 */
	private String validate(String user, String password, String email,
			String name) {
		if (user.isEmpty() || password.isEmpty() || email.isEmpty()
				|| name.isEmpty())
			return "All fields are required.";
		else if (!email
				.matches("[A-Za-z]+([.]*[\\w0-9_-]*)*@[A-Za-z]+[\\w0-9_-]*[.](com|org|net|edu)"))
			return "Email address must be valid";
		else
			return null;
	}

	public boolean register(String username, String password, String email,
			String name) {
		return userList.createUser(username, password, email, name);
	}

	/**
	 * Opens up the Registration popup.
	 */
	public void showPopup() {

		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		popupView = inflater.inflate(R.layout.registerpopup,
				(ViewGroup) findViewById(R.id.login_popup));
		if (popup == null) {
			popup = new PopupWindow(popupView, 400, 620, true);
		}
		popup.showAtLocation(popupView, Gravity.CENTER, 0, 0);

		Button cancelButton = (Button) popupView
				.findViewById(R.id.p_cancel_button);
		Button registerButton = (Button) popupView
				.findViewById(R.id.p_register_button);
		final EditText usernameText = (EditText) popupView
				.findViewById(R.id.p_username);
		final EditText passwordText = (EditText) popupView
				.findViewById(R.id.p_password);
		final EditText emailText = (EditText) popupView.findViewById(R.id.p_email);
		final EditText nameText = (EditText) popupView.findViewById(R.id.p_name);
		final TextView resultTextView = (TextView) popupView
				.findViewById(R.id.p_result);
		

		cancelButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				popup.dismiss();
			}
		});

		/**
		 * Button listener
		 */
		registerButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String username = usernameText.getText().toString();
				String password = passwordText.getText().toString();
				String email = emailText.getText().toString();
				String name = nameText.getText().toString();
				Log.d("kefu", "before validate");

				String result = validate(username, password, email, name);
				Log.d("kefu", result == null ? "null" : result);
				if (result != null)
					resultTextView.setText(result);
				else {
					boolean r = register(username, password, email, name);
					if (r) {

						lblResult
								.setText("Account created; you may now log in.");
						popup.dismiss();
					} else {
						resultTextView
								.setText("This username is already registered.");
					}
				}
			}

		});
	}
}